﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.ApplicationPages;
using Microsoft.SharePoint.Administration;
using SPThumbnailExtender.Interne;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using System.IO;

namespace SPThumbnailExtender.Layouts.SPThumbnailExtender
{
    public partial class CreateDatabase : GlobalAdminPageBase
    {
        protected void btnResetCnxStr_Click(object sender, EventArgs e)
        {
            Helper.SetParameter("SPThumbnailExtender.ConnectionString", txtConnectionString.Text);
            Response.Redirect("/generalapplicationsettings.aspx");
        }
        protected void btnGenerate_Click(object sender, EventArgs e)
        {
            string DatabaseName;
            string strCnxMaster = GenerateCNXMaster(txtConnectionString.Text, out DatabaseName);
            using (SqlConnection cndata = new SqlConnection(strCnxMaster))
            {
                cndata.Open();

                using (SqlCommand cmdata = new SqlCommand())
                {
                    cmdata.Connection = cndata;
                    cmdata.CommandText = "CREATE DATABASE [" + DatabaseName + "]";
                    cmdata.ExecuteNonQuery();

                }
                cndata.Close();
            
            }
            using (SqlConnection cndata = new SqlConnection(txtConnectionString.Text))
            {
                cndata.Open();
                using (SqlCommand cmdata = new SqlCommand())
                {
                    cmdata.Connection = cndata;
                    StreamReader reader = new StreamReader(typeof(CreateDatabase).Assembly.GetManifestResourceStream("SPThumbnailExtender.SPThumbnailExtenderDBCache.sql"));
                    string strCreateDB = reader.ReadToEnd();
                    strCreateDB = string.Format(strCreateDB, DatabaseName);
                    string[] aStrCreateDB = strCreateDB.Split(';');
                    foreach (string strCommand in aStrCreateDB)
                    {
                        cmdata.CommandText = strCommand;
                        cmdata.ExecuteNonQuery();
                    }
                }
                cndata.Close();
            }
            Helper.SetParameter("SPThumbnailExtender.ConnectionString", txtConnectionString.Text);
            Response.Redirect("/generalapplicationsettings.aspx");
            
        }

        private string GenerateCNXMaster(string ConnectionString, out string DataBaseName)
        {
            string[] arStrParameter = ConnectionString.Split(';');
            List<string> lstStrParameter = new List<string>();
            string strDataBaseName="";
            foreach (string strParameter in arStrParameter)
            {
                string strParameterReturn=strParameter;
                if (strParameter.ToLower().Contains("initial") || strParameter.ToLower().Contains("database"))
                {
                    strDataBaseName=strParameter.ToLower().Replace("initial catalog=", "").Replace("database=", "").Trim();
                    strParameterReturn=strParameter.ToLower().Replace(strDataBaseName,"master");
                }
                lstStrParameter.Add(strParameterReturn);
            }
            DataBaseName= strDataBaseName;
            return string.Join(";", lstStrParameter.ToArray());
        }
        protected void btnReset_Click(object sender, EventArgs e)
        {
            string DatabaseName;
            string strCnxMaster = GenerateCNXMaster(txtConnectionString.Text, out DatabaseName);
            using (SqlConnection cndata = new SqlConnection(strCnxMaster))
            {
                cndata.Open();

                using (SqlCommand cmdata = new SqlCommand())
                {
                    cmdata.Connection = cndata;
                    cmdata.CommandText = "ALTER DATABASE [" + DatabaseName + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE";
                    cmdata.ExecuteNonQuery();

                }
                using (SqlCommand cmdata = new SqlCommand())
                {
                    cmdata.Connection = cndata;
                    cmdata.CommandText = "Drop DATABASE [" + DatabaseName + "]";
                    cmdata.ExecuteNonQuery();

                }
                cndata.Close();

            }

            btnGenerate_Click(sender, e);
            Response.Redirect("/generalapplicationsettings.aspx");
        }
        protected void Page_Load(object sender, EventArgs e)
        {

            if(!Page.IsPostBack && Helper.GetParameter("SPThumbnailExtender.ConnectionString")!=null)
                txtConnectionString.Text =Helper.GetParameter("SPThumbnailExtender.ConnectionString").ToString();
        }
    }
}
